/*
 * Copyright (c) $today.year-Now http://www.zxpnet.com All rights reserved.
 */

package com.zxp.springboot.listener;

import cn.hutool.core.util.StrUtil;
import com.zxp.hello.properties.HelloProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 启动时只执行一次
 * @desc:
 * @author: shollin
 * @date: 2021/6/19/019 22:46
 */
@Component
@Order(2)
@Slf4j
public class MyCommandLineRunner implements CommandLineRunner {

    @Autowired
    HelloProperties helloProperties;

    @Value("${server.port:8080}")
    private Integer port;

    @Value("${spring.profiles.active:'dev'}")
    private String profile;

    @Value("${server.servlet.context-path:'/'}")
    private String contextPath;

    @Override
    public void run(String... args) throws Exception {
      log.info("MyCommandLineRunner run "+args);

      if(helloProperties.getIsOpen() && StrUtil.equalsIgnoreCase(profile,"dev")){
          String url = StrUtil.format(" http://localhost:{}{}",port,contextPath);

          // windows运行:  cmd /c start 或者 rundll32 url.dll,FileProtocolHandler
          // mac运行 open -a GoogleChrome
          String runCmd = "rundll32 url.dll,FileProtocolHandler "+ url;
          String runCmd2 = "cmd /c start "+ url;
          String runCmdMac = "open -a GoogleChrome "+ url;

          Runtime run = Runtime.getRuntime();
          try {
              run.exec(runCmd);
              log.info("启动浏览器打开项目成功");
          } catch (Exception e) {
              e.printStackTrace();
              System.out.println("启动项目自动打开浏览器失败");
          }
      }


    }
}
